package com.czk.model.ptotorype.practice.deepcopy;

import java.io.*;

/**
 *
 * @Author:ChenZhangKun
 * @Date: 2020/8/19 23:32
 */
public class Person implements Cloneable,Serializable{

    private static final long SERIALIZALEID=123456679L;
    /**
     * 引用对象
     */
    private Clothes clothes;
    /**
     * 基本数据类型
     */
    private String name;
    /**
     * 基本数据类型
     */
    private  int age;

    public Clothes getClothes() {
        return clothes;
    }

    public void setClothes(Clothes clothes) {
        this.clothes = clothes;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "clothes=" + clothes +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    /**
     * 浅拷贝的实现
     * 引用变量运用同一块内存地址
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person person=(Person) super.clone();
        // 对象也要clone
        person.clothes=(Clothes) this.clothes.clone();
        return person;
    }

    /**
     * 序列化和反序列化实现深拷贝
     * @return clone对象
     */
    public Object deepClone(){
        ByteArrayInputStream byteArrayInputStream=null;
        ByteArrayOutputStream byteArrayOutputStream=null;
        ObjectInputStream objectInputStream=null;
        ObjectOutputStream objectOutputStream=null;
        Person person=null;
        try {
            byteArrayOutputStream=new ByteArrayOutputStream();
            objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);
            byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            objectInputStream=new ObjectInputStream(byteArrayInputStream);
            person=(Person)objectInputStream.readObject();

        }catch (IOException ex){
            ex.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return person;
    }
}
